package com.neusoft.lohas.modules.shop.web.mall;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.google.common.collect.Lists;
import com.neusoft.lohas.common.config.Global;
import com.neusoft.lohas.common.pay.PayBase;
import com.neusoft.lohas.common.pay.payutil.alipay.util.UtilDate;
import com.neusoft.lohas.common.persistence.StatusBean;
import com.neusoft.lohas.common.utils.CookieUtils;
import com.neusoft.lohas.common.utils.DateUtils;
import com.neusoft.lohas.common.utils.FloatFormat;
import com.neusoft.lohas.common.utils.IdGen;
import com.neusoft.lohas.common.utils.JsonUtil;
import com.neusoft.lohas.common.utils.PinYinHeadCharUtil;
import com.neusoft.lohas.common.utils.StringUtils;
import com.neusoft.lohas.common.web.BaseShopController;
import com.neusoft.lohas.modules.api.SmsControllerAPI;
import com.neusoft.lohas.modules.ivm.entity.business.ActivityProduct;
import com.neusoft.lohas.modules.ivm.entity.business.HangStore;
import com.neusoft.lohas.modules.ivm.entity.mall.Index;
import com.neusoft.lohas.modules.ivm.entity.mall.IndexPhoto;
import com.neusoft.lohas.modules.ivm.entity.merchant.DeliveryFee;
import com.neusoft.lohas.modules.ivm.entity.merchant.Merchant;
import com.neusoft.lohas.modules.ivm.entity.merchant.ReceiptTime;
import com.neusoft.lohas.modules.ivm.entity.merchant.TimeSlot;
import com.neusoft.lohas.modules.ivm.entity.order.DeliveryDetail;
import com.neusoft.lohas.modules.ivm.entity.order.DeliveryInfo;
import com.neusoft.lohas.modules.ivm.entity.order.Order;
import com.neusoft.lohas.modules.ivm.entity.order.OrderDetail;
import com.neusoft.lohas.modules.ivm.entity.order.OrderDetailItem;
import com.neusoft.lohas.modules.ivm.entity.order.Prompt;
import com.neusoft.lohas.modules.ivm.entity.order.ShoppingCart;
import com.neusoft.lohas.modules.ivm.entity.order.UserAddress;
import com.neusoft.lohas.modules.ivm.entity.product.Product;
import com.neusoft.lohas.modules.ivm.entity.product.ProductClassify;
import com.neusoft.lohas.modules.ivm.enums.order.OrderTypeEnum;
import com.neusoft.lohas.modules.ivm.enums.order.PayStatusEnum;
import com.neusoft.lohas.modules.ivm.enums.sys.MessageEnum;
import com.neusoft.lohas.modules.ivm.service.business.ActivityService;
import com.neusoft.lohas.modules.ivm.service.business.HangStoreService;
import com.neusoft.lohas.modules.ivm.service.mall.IndexPhotoService;
import com.neusoft.lohas.modules.ivm.service.merchant.DeliveryFeeService;
import com.neusoft.lohas.modules.ivm.service.merchant.MerchantService;
import com.neusoft.lohas.modules.ivm.service.merchant.TimeSlotService;
import com.neusoft.lohas.modules.ivm.service.order.DeliveryDetailService;
import com.neusoft.lohas.modules.ivm.service.order.DeliveryInfoService;
import com.neusoft.lohas.modules.ivm.service.order.PromptService;
import com.neusoft.lohas.modules.ivm.service.order.UserAddressService;
import com.neusoft.lohas.modules.ivm.service.order.orderDetailItemService;
import com.neusoft.lohas.modules.ivm.service.product.ProductService;
import com.neusoft.lohas.modules.shop.service.ShopService;
import com.neusoft.lohas.modules.shop.utils.ShopUtils;
import com.neusoft.lohas.modules.sys.entity.User;
import com.neusoft.lohas.modules.sys.service.SystemService;
import com.neusoft.lohas.modules.sys.utils.UserUtils;

@Controller
@RequestMapping(value = "${frontPath}")
public class ShopingController extends BaseShopController {
	
	@Autowired
	private ShopService shopService;
	@Autowired
	private ProductService productService;
	@Autowired
	private MerchantService merchantService;
	@Autowired
	private DeliveryFeeService deliveryFeeService;
	@Autowired
	private UserAddressService userAddressService;
	@Autowired
	private IndexPhotoService indexPhotoService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private PromptService promptService;
	@Autowired
	private DeliveryInfoService deliveryInfoService;
	@Autowired
	private DeliveryDetailService deliveryDetailService;
	@Autowired
	private orderDetailItemService orderDetailItemService;
	@Autowired
	private TimeSlotService timeSlotService;
	@Autowired
	private HangStoreService hangStoreService;
	
	//
	private JsonUtil jsonUtil = new JsonUtil();
	@Qualifier("smsControllerAPI")
	@Autowired
	private SmsControllerAPI smsControllerAPI;
	
	/**
	 * 跳转到最新优惠页面
	 * @param concession
	 * @param sid
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = {"index", ""})
	public String showConcession(
			HttpServletRequest request, HttpServletResponse response, Model model){
		List<IndexPhoto> photoList = indexPhotoService.findList();
		Index index = new Index();
		index.setPhotoList(photoList);
		model.addAttribute("index", index);
		return "redirect:"+Global.getFrontPath()+"shops/shoping/goodList";
		//return "modules/mall/index";
	}
	
	/**
	 * 用户进入商户主页，显示商户下的商品列表
	 * @param model
	 */
	@RequestMapping(value = "shops/shoping/goodList")
	public String goodList(
			@RequestParam(value="sid", required=false, defaultValue="83597da0b1b241d7ace669ef0bb84005")String sid,
			@RequestParam(value="classifyId", required=false, defaultValue="66f1373b8e0f42f1a099ab7388a311df")String classifyId,
			HttpServletRequest request, Model model){
		/**获取商户信息*/
		String choiceClassifyId =  "";
		Merchant merchant = ShopUtils.getMerchantById(sid);
		List<HangStore> stores = hangStoreService.findList(sid);
		if (stores.size()>0) {
			String cookieChoiceClassifyId = CookieUtils.getCookie(request, "choiceClassifyId");
			boolean isExists = false;
			for (HangStore hangStore : stores) {
				for (ProductClassify bean : hangStore.getClassify().getChildList()) {
					if (bean.getId().equals(cookieChoiceClassifyId)) {
						isExists = true; break;
					}
				}
				if (isExists) {
					break;
				}
			}
			if (isExists) {
				choiceClassifyId = cookieChoiceClassifyId;
			}else {
				choiceClassifyId = stores.get(0).getClassify().getChildList().get(0).getId();
			}
		}
		/**获取商品列表*/
		model.addAttribute("stores", stores);
		model.addAttribute("classifyId", classifyId);
		model.addAttribute("choiceClassifyId", choiceClassifyId);
		model.addAttribute("merchant", merchant);
		model.addAttribute("sid", sid);
		return "modules/mall/good_list";
	}
	
//	/**
//	 * 用户进入商户主页，显示商户下的商品列表
//	 * @param model
//	 */
//	@RequestMapping(value = "shops/shoping/goodList")
//	public String goodList(
//			@RequestParam(value="sid", required=false, defaultValue="83597da0b1b241d7ace669ef0bb84005")String sid,
//			@RequestParam(value="classifyId", required=false, defaultValue="66f1373b8e0f42f1a099ab7388a311df")String classifyId,
//			HttpServletRequest request, Model model){
//		/**获取商户信息*/
//		String choiceClassifyId =  "";
//		Merchant merchant = ShopUtils.getMerchantById(sid);
//		Product product = new Product();
//		List<ProductClassify> classifies = Lists.newArrayList();
//		
//		/**获取二级分类*/
//		classifies = ShopUtils.getClassifyTwoList(sid, classifyId);
//		product.setClassify(new ProductClassify(classifyId));
//		if (classifies.size()>0) {
//			List<String> classifyIdList = Lists.newArrayList();
//			String cookieChoiceClassifyId = CookieUtils.getCookie(request, "choiceClassifyId");
//			boolean isExists = false;
//			for (ProductClassify bean : classifies) {
//				if (bean.getId().equals(cookieChoiceClassifyId)) {
//					isExists = true; break;
//				}
//			}
//			if (isExists) {
//				choiceClassifyId = cookieChoiceClassifyId;
//			}else {
//				choiceClassifyId = classifies.get(0).getId();
//			}
//			classifyIdList.add(classifies.get(0).getId());
//			
//			product.setClassifyIdList(classifyIdList);
//		}
//		/**获取商品列表*/
////		List<Product> products = shopService.findProducts(sid, product, "classify");
//		model.addAttribute("classifies", classifies);
////		model.addAttribute("list", products);
//		model.addAttribute("classifyId", classifyId);
//		model.addAttribute("choiceClassifyId", choiceClassifyId);
//		model.addAttribute("merchant", merchant);
//		model.addAttribute("sid", sid);
//		return "modules/mall/good_list";
//	}
	
	/**
	 * 
	 * @param sid
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = {"shops/shoping/goodList/productList"})
	@ResponseBody
	public List<Product> goodList(String sid,
			String classifyId, 
			HttpServletRequest request, HttpServletResponse response, Model model){
		Product product = new Product();
		List<String> classifyIdList = Lists.newArrayList();
		classifyIdList.add(classifyId);
		product.setClassifyIdList(classifyIdList);
		List<Product> products = shopService.findProducts(sid, product, "classify");
		return products;
	}
	
	/**
	 * 用户进入商户主页，显示商户下的商品列表
	 * @param sid
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "shops/shoping/goodInfo/productDetail")
	public String productDetail(
			Product product,
			String sid,
			@RequestParam(value="classifyId", required=false, defaultValue="")String classifyId,
			@RequestParam(value="shopModel", required=false, defaultValue="merchant")String shopModel,
			HttpServletRequest request, HttpServletResponse response, Model model){
		Merchant merchant = ShopUtils.getMerchantById(sid);
		product = productService.get(product.getId());
		List<ShoppingCart> list = shopService.findShoppingCarts(sid, null);
		//定义保存购买总数量和总金额变量
		int totalNumber=0;
		double totalAmount=0.00;
		for (ShoppingCart cart : list) {
			Product bean = cart.getProduct();
			bean.setCartId(cart.getId());
			bean.setNumber(cart.getNumber()); 
			bean.setAmount(cart.getAmount());
			if (bean.getId().equals(product.getId())) {
				product = bean;
			}
			totalNumber += cart.getNumber();
			totalAmount += cart.getAmount();
		}
		model.addAttribute("product", product);
		model.addAttribute("totalNumber", totalNumber);
		model.addAttribute("totalAmount", FloatFormat.m2(totalAmount));
		model.addAttribute("merchant", merchant);
		model.addAttribute("classifyId", classifyId);
		model.addAttribute("shopModel", shopModel);
		model.addAttribute("sid", sid);
		return "modules/mall/good_info";
	}
	
	@RequestMapping(value = "shops/shoping/shopCart")
	public String shopCart(
			String sid, 
			@RequestParam(value="classifyId", required=false, defaultValue="")String classifyId,
			@RequestParam(value="shopModel", required=false, defaultValue="merchant")String shopModel,
			HttpServletRequest request, HttpServletResponse response, Model model){
		Merchant merchant = ShopUtils.getMerchantById(sid);
		//获取派送费信息
		DeliveryFee deliveryFee = deliveryFeeService.findByMerchantId(merchant.getId());
		if(StringUtils.isBlank(deliveryFee.getOpenState()) || deliveryFee.getOpenState().equals("0")){
			model.addAttribute("lowFee", 0);
			model.addAttribute("fee", 0);
		}else{
			model.addAttribute("lowFee", deliveryFee.getLowFee());
			model.addAttribute("fee", deliveryFee.getAmount());
		}
		model.addAttribute("merchant", merchant);
		model.addAttribute("sid", sid);
		model.addAttribute("classifyId", classifyId);
		model.addAttribute("shopModel", shopModel);
		return "modules/mall/cart_list";
	}
	
	/**
	 * 去结算跳转
	 * @param sid
	 * @param mobile
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "shops/shoping/orderInfo/toSettlement")
	public String toSettlement(
			String sid, 
			@RequestParam(value="classifyId", required=false, defaultValue="")String classifyId,
			@RequestParam(value="shopModel", required=false, defaultValue="merchant")String shopModel,
			@RequestParam(value="totalNumber", required=false, defaultValue="0")Double totalNumber,
			@RequestParam(value="amount", required=false, defaultValue="0")Double amount,
			HttpServletRequest request, HttpServletResponse response, Model model){
		Merchant merchant = ShopUtils.getMerchantById(sid);
		//获取商户收货时间段数据
		ReceiptTime receiptTime = shopService.getReceiptTime(merchant);
		//获取派送费信息
		DeliveryFee deliveryFee = deliveryFeeService.findByMerchantId(merchant.getId());
		if(StringUtils.isBlank(deliveryFee.getOpenState()) || deliveryFee.getOpenState().equals("0")){
			model.addAttribute("lowFee", 0);
			model.addAttribute("fee", 0);
		}else{
			model.addAttribute("lowFee", deliveryFee.getLowFee());
			model.addAttribute("fee", deliveryFee.getAmount());
		}
		model.addAttribute("receiptTime", receiptTime);
		model.addAttribute("merchant", merchant);
		model.addAttribute("classifyId", classifyId);
		model.addAttribute("shopModel", shopModel);
		model.addAttribute("totalNumber", totalNumber);
		model.addAttribute("amount", amount);
		model.addAttribute("sid", sid);
		return "modules/mall/order_info";
	}
	
	/**
	 * 订单提交
	 * @param order
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "shops/shoping/orderSuccess/save")
	public String save(
			Order order,
			@RequestParam(value="classifyId", required=false, defaultValue="")String classifyId,
			@RequestParam(value="totalCount", required=false, defaultValue="0")Double totalCount,
			@RequestParam(value="totalAmount", required=false, defaultValue="0")Double totalAmount,
			@RequestParam(value="name", required=false, defaultValue="")String name,
			@RequestParam(value="phone", required=false, defaultValue="")String phone,
			@RequestParam(value="province", required=false, defaultValue="")String province,
			@RequestParam(value="city", required=false, defaultValue="")String city,
			@RequestParam(value="country", required=false, defaultValue="")String country,
			@RequestParam(value="address", required=false, defaultValue="")String address,
			@RequestParam(value="defaultFlag", required=false, defaultValue="1")String defaultFlag,
			@RequestParam(value="cars", required=false, defaultValue="")String cars,
			@RequestParam(value="userId", required=false, defaultValue="")String userId,
			Model model, RedirectAttributes redirectAttributes){
		User user = systemService.getUser(userId);
		if(user==null){
			user = UserUtils.getShopUser(phone, name);
		}
		//商户信息
		Merchant merchant = merchantService.get(order.getMerchant().getId());
		order.setOrderNo(createUniqeAuthCode(merchant.getName(), merchant.getId()));
		order.setPayStatus(String.valueOf(PayStatusEnum.NOT_PAY.getStatus()));
		order.setOrderType(String.valueOf(OrderTypeEnum.READY_FOR_DELIVERY.getType()));
		
		//收货地址
		UserAddress userAddress=userAddressService.getByNameAndPhone(name, phone);
		if(null==userAddress){
			userAddress=new UserAddress();
		}
		userAddress.setName(name);
		userAddress.setPhone(phone);
		userAddress.setProvince(province);
		userAddress.setCity(city);
		userAddress.setCounty(country);
		userAddress.setAddress(address);
		userAddress.setDefaultFlag(Integer.parseInt(defaultFlag));
		userAddress.setCreateDate(new Date());
		userAddress.setCreateBy(user);
		userAddress.setUpdateBy(user);
		userAddress.setUser(user);
		userAddressService.save(userAddress);
		
		order.setUserAddress(userAddress);
		order.setUser(user);
		order.setCreateBy(user);
		order.setUpdateBy(user);
		order.setCreateDate(new Date());
		
		//设置总金额总数量
		order.setTotalNumber(totalCount.intValue());
		order.setAmount(totalAmount);
		
		List<OrderDetail> detailList = Lists.newArrayList(); // 订单详情列表
		if(null!=cars && !"".equals(cars)){
			cars=cars.replace("},{", "}-_-{");
			String[] carArray = cars.split("-_-");
			if(null!=carArray && carArray.length>0){
				for (int i = 0; i < carArray.length; i++) {
					JSONArray array = JSONArray.fromObject("["+carArray[i]+"]");
			        JSONObject o = JSONObject.fromObject(array.get(0));
					//订单明细
					OrderDetail detail = new OrderDetail();
					detail.setId(IdGen.uuid());
					detail.setMerchant(merchant);
					Product product=productService.get(o.get("id").toString());
					detail.setProduct(product);
					detail.setNumber(o.get("number")==null?1:Integer.parseInt(o.get("number").toString()));
					detail.setPrice(o.get("price")==null?1:Double.parseDouble(o.get("price").toString()));
					detail.setAmount(detail.getPrice()*detail.getNumber());
					detail.setUser(user);
					detail.setOrder(order);
					detail.setCreateBy(user);
					detail.setUpdateBy(user);
					detail.prePersist();
					detailList.add(detail);
				}
			}
		}
		
		//获取赠送活动商品
		List<ActivityProduct> apList = activityService.getActivityProducts(merchant.getId(), order.getAmount(), order.getCreateDate());
		for (ActivityProduct activityProduct : apList) {
			OrderDetail detail = new OrderDetail();
			detail.setId(IdGen.uuid());
			detail.setType(1);//赠品
			detail.setMerchant(merchant);
			detail.setProduct(activityProduct.getProduct());
			detail.setNumber(activityProduct.getNumber());
			detail.setPrice(activityProduct.getPrice());
			detail.setAmount(activityProduct.getNumber()*activityProduct.getPrice());
			detail.setUser(user);
			detail.setOrder(order);
			detail.setCreateBy(user);
			detail.setUpdateBy(user);
			detail.prePersist();
			detailList.add(detail);
		}
		
		order.setDetailList(detailList);
		
		shopService.saveOrder(order);
		
		//将订单信息备份到送货单中deliveryInfo,作用：初始化送货单
		DeliveryInfo deliveryInfo = new DeliveryInfo();
    	//主键ID
    	String deliveryInfoId = IdGen.uuid();
    	deliveryInfo.setId(deliveryInfoId);
    	//温馨提示
    	Prompt prompt = promptService.findByMerchantId(order.getMerchant().getId());
    	deliveryInfo.setPrompt(prompt.getPrompt());
    	deliveryInfo.setOrder(order);
    	//收货人信息
    	UserAddress user_address = userAddressService.get(order.getUserAddress().getId());
    	deliveryInfo.setName(user_address.getName());
    	deliveryInfo.setPhone(user_address.getPhone());
    	deliveryInfo.setAddress(user_address.getDetailAddress());
    	//根据选择的时间段，计算送货日期
    	Date createTime = order.getCreateDate();//下单时间
    	Date signDate = createTime;//收获日期
    	String signTime = ""; //收货时间
    	if(order.getTimeSlot()!=null){
    		TimeSlot slot = timeSlotService.get(order.getTimeSlot().getId());
			deliveryInfo.setStartTime(slot.getStartTime());
			deliveryInfo.setEndTime(slot.getEndTime());
			deliveryInfo.setTimeText(slot.getTimeText());
			signTime = slot.getTimeText();
		}
		//初始化送货日期
    	String deliveryTime = "";
		if(signTime != null && signTime.indexOf("次日")>-1){
			signDate = DateUtils.GetLastDate(createTime, 1);
			deliveryTime = signTime.substring(2).trim();
		}else if(signTime != null && signTime.indexOf("后日")>-1){
			signDate = DateUtils.GetLastDate(createTime, 2);
			deliveryTime = signTime.substring(2).trim();
		}
		deliveryInfo.setDeliveryDate(signDate);
		deliveryInfo.setDeliveryTime(deliveryTime);
    	deliveryInfo.setAmount(order.getAmount());
    	deliveryInfo.setRefund(0);
		deliveryInfo.setDeliveryNo(createUniqeAuthCode(order.getOrderNo()));//生成送货单号
		//封装派送单清单deliveryDetail
		List<DeliveryDetail> deliveryDetails = getOrderList(order);
		//封装订单备份清单orderDetailItem
		List<OrderDetailItem> orderDetailItems = getOrderItemList(order);
		deliveryInfoService.save(deliveryInfo);
		deliveryDetailService.save(deliveryDetails);
		orderDetailItemService.save(orderDetailItems);
		System.out.println("派送单信息初始化完成.");
		
		addMessage(redirectAttributes, "订单提交成功，返回可继续购买哦.");
		redirectAttributes.addFlashAttribute("sysMess", true);
		redirectAttributes.addFlashAttribute("classifyId", classifyId);
		return "redirect:"+Global.getFrontPath()+"shops/shoping/orderDetail/detail?sid="+merchant.getId()+"&orderNo="+order.getOrderNo()+"&classifyId="+classifyId+"&userId="+user.getId();
	}
	
	//封装订单商品详情list
	private List<DeliveryDetail> getOrderList(Order order) {
		//订单商品list
		List<DeliveryDetail> details = new ArrayList<DeliveryDetail>();
		int i=0;
		for (OrderDetail detail : order.getDetailList()) {
			DeliveryDetail deliveryDetail = new DeliveryDetail();
			deliveryDetail.setSort(i);
			deliveryDetail.setId(IdGen.uuid());
			deliveryDetail.setType(detail.getType());
			deliveryDetail.setMerchant(detail.getMerchant());
			deliveryDetail.setOrder(detail.getOrder());
			deliveryDetail.setProduct(detail.getProduct());
			deliveryDetail.setUser(detail.getUser());
			deliveryDetail.setNumber(detail.getNumber());
			deliveryDetail.setPrice(detail.getPrice());
			deliveryDetail.setAmount(detail.getAmount());
			details.add(deliveryDetail);
			i++;
		}
		return details;
	}
	
	//封装订单商品备份详情list
	private List<OrderDetailItem> getOrderItemList(Order order) {
		//订单商品list
		List<OrderDetailItem> details = new ArrayList<OrderDetailItem>();
		int i=0;
		for (OrderDetail detail : order.getDetailList()) {
			OrderDetailItem orderDetailItem = new OrderDetailItem();
			orderDetailItem.setSort(i);
			orderDetailItem.setId(IdGen.uuid());
			orderDetailItem.setType(detail.getType());
			orderDetailItem.setMerchant(detail.getMerchant());
			orderDetailItem.setOrder(detail.getOrder());
			orderDetailItem.setProduct(detail.getProduct());
			orderDetailItem.setUser(detail.getUser());
			orderDetailItem.setNumber(detail.getNumber());
			orderDetailItem.setPrice(detail.getPrice());
			orderDetailItem.setAmount(detail.getAmount());
			details.add(orderDetailItem);
			i++;
		}
		return details;
	}
	
	//订单编号
	public String createUniqeAuthCode(String merchantName, String merchantId) {
		SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmssSSS");// 设置日期格式
		String orderNo = df.format(new Date());// new Date()为获取当前系统时间
		String fourRandom = "";//根据订单数生成4位数
		int orderNums = shopService.getOrderNumsByDate(merchantId)+1;//获取当日订单总数
		fourRandom = UtilDate.getFourStr(orderNums+"");
		String merchantSP = PinYinHeadCharUtil.getPinYinHeadChar(merchantName);
		if(merchantSP.length()>4){
			merchantSP = merchantSP.substring(0, 4);//商户名前四位
		}
		String authCode = "PR"+merchantSP+orderNo.substring(0, 6) + fourRandom;
		return authCode;
	}
	
	//送货单号
	public String createUniqeAuthCode(String orderNo) {
		String authCode = "D"+orderNo.substring(2);
		return authCode;
	}
	
	/**
	 * 订单详情
	 * @param sid
	 * @param orderNo
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "shops/shoping/orderDetail/detail")
	public String orderDetail(
			String sid, 
			String orderNo, 
			@RequestParam(value="classifyId", required=false, defaultValue="")String classifyId,
			@RequestParam(value="mode", required=false, defaultValue="")String mode,
			@RequestParam(value="userId", required=false, defaultValue="")String userId,
			HttpServletRequest request, HttpServletResponse response, Model model){
		Merchant merchant = ShopUtils.getMerchantById(sid);
		Order order = shopService.findByOrderNo(orderNo);
		if (null==order) {
			return "redirect:"+Global.getFrontPath()+"/shops/sysAlert?code="+MessageEnum.NOT_EXISTS_ORDER.getCode();
		}
		model.addAttribute("order", order);
		model.addAttribute("merchant", merchant);
		
		model.addAttribute("sid", sid);
		model.addAttribute("classifyId", classifyId);
		model.addAttribute("mode", mode);
		model.addAttribute("userId", userId);
		return "modules/mall/order_detail";
	}
	
	/**
	 * 跳转登录
	 * @param model
	 */
	@RequestMapping(value = "shops/shoping/toLogin")
	public String toLogin(
			String sid,
			@RequestParam(value="classifyId", required=false, defaultValue="")String classifyId,
			HttpServletRequest request, Model model){
		model.addAttribute("classifyId", classifyId);
		model.addAttribute("sid", sid);
		return "modules/mall/login";
	}
	
	/**
	 * 异步手机验证码登录
	 */
	@SuppressWarnings("static-access")
	@RequestMapping(value = "shops/shoping/wxSendCheckCode")
	@ResponseBody
	public StatusBean<String> sendCheckCode(
			String mobile, 
			HttpServletRequest request, HttpServletResponse response, Model model) {
		String jsonData = smsControllerAPI.sendCheckCode(mobile);
		try {
			com.neusoft.lohas.common.utils.StatusBean result = jsonUtil.objectMapper.readValue(jsonData, new TypeReference<com.neusoft.lohas.common.utils.StatusBean>(){});
			if(result.getStatus()==200){
				return new StatusBean<String>(result.getMessage(), 200, "发送成功");
			}else {
				return new StatusBean<String>(null, 500, "发送失败");
			}
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new StatusBean<String>(null, 500, "发送失败");
	}
	
	/**
	 * 异步手机验证码登录
	 */
	@RequestMapping(value = "shops/shoping/wxLoginCheckCode")
	@ResponseBody
	public StatusBean<User> loginCheckCodeAjax(
			String mobile, 
			HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getShopUser(mobile, mobile);
		if(null!=user && StringUtils.isNotBlank(user.getId())){
			//登录成功
			return new StatusBean<User>(user, 200, "登录成功");
		}else{
			//登录失败
			return new StatusBean<User>(null, 500, "登录失败");
		}
	}
	
	/**
	 * 异步登录
	 */
	@RequestMapping(value = "shops/shoping/wxLoginAjax")
	@ResponseBody
	public StatusBean<User> loginAjax(
			String mobile, 
			String password, 
			HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = systemService.wxLogin(mobile, password);
		if(null!=user && StringUtils.isNotBlank(user.getId())){
			//登录成功
			return new StatusBean<User>(user, 200, "登录成功");
		}else{
			//登录失败
			return new StatusBean<User>(null, 500, "登录失败");
		}
	}
	
	/**
	 * 异步注册
	 */
	@RequestMapping(value = "shops/shoping/wxRegisterCheckCode")
	@ResponseBody
	public StatusBean<User> wxRegisterCheckCode(
			String mobile,
			String password,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getShopUser(mobile, mobile, password);
		if(null!=user && StringUtils.isNotBlank(user.getId())){
			//注册成功
			return new StatusBean<User>(user, 200, "注册成功");
		}else{
			//注册失败
			return new StatusBean<User>(null, 500, "注册失败");
		}
	}
	
	/**
	 * 异步注册
	 */
	@RequestMapping(value = "shops/shoping/wxRegister")
	@ResponseBody
	public StatusBean<User> wxRegister(
			String name,
			String mobile,
			String password,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getShopUser(mobile, name, password);
		if(null!=user && StringUtils.isNotBlank(user.getId())){
			//注册成功
			return new StatusBean<User>(user, 200, "注册成功");
		}else{
			//注册失败
			return new StatusBean<User>(null, 500, "注册失败");
		}
	}
	
	/**
	 * wx端-我的订单
	 * @param userId
	 * @param type
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "shops/shoping/myOrder/orderList")
	public String myOrderList(
			@RequestParam(value="type", required=true, defaultValue="1")int type,
			HttpServletRequest request, HttpServletResponse response, Model model){
		String userId = CookieUtils.getCookie(request, "userId");
		Order order = new Order();
		order.setUser(new User(userId));
		List<Order> orders = shopService.findMyOrderList(order, type);
		User user = UserUtils.getUserById(order.getUser().getId());
		List<Long> list = Lists.newArrayList();
		list.add(shopService.findMyOrderCount(order, 1));
		list.add(shopService.findMyOrderCount(order, 2));
		list.add(shopService.findMyOrderCount(order, 3));
		list.add(shopService.findMyOrderCount(order, 4));
		list.add(shopService.findMyOrderCount(order, 5));
		list.add(shopService.findMyOrderCount(order, 6));
		list.add(shopService.findMyOrderCount(order, 7));
		model.addAttribute("list", list);
		model.addAttribute("orders", orders);
		model.addAttribute("user", user);
		model.addAttribute("userId", userId);
		model.addAttribute("type", type);
		return "modules/mall/orderList";
	}
	
	/**
	 * 订单详情
	 * @param orderNo
	 * @param mobile
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "shops/shoping/myOrder/orderDetail")
	public String orderDetail(
			String orderNo, 
			@RequestParam(value="type", required=true, defaultValue="0")int type,
			@RequestParam(value="userId", required=false, defaultValue="") String userId,
			HttpServletRequest request, HttpServletResponse response, Model model){
		String cookieUserId = CookieUtils.getCookie(request, "userId");
		if(StringUtils.isBlank(userId) && StringUtils.isNotBlank(cookieUserId)){
			userId = cookieUserId;
		}
		User user = UserUtils.getUserById(userId);
		Order order = shopService.findByOrderNo(orderNo);
		if (order==null) {
			return "redirect:"+Global.getFrontPath()+"/shops/sysAlert?code="+MessageEnum.NOT_EXISTS_ORDER.getCode();
		}
		model.addAttribute("order", order);
		model.addAttribute("user", user);
		model.addAttribute("userId", userId);
		model.addAttribute("type", type);
		model.addAttribute("mobile", user.getMobile());
		model.addAttribute("myorder", "myorder");
		return "modules/mall/order_detail";
	}
	
	@RequestMapping(value = "shops/shoping/order/toPay")
	public String orderToPay(
			String orderNo, 
			@RequestParam(value="type", required=true, defaultValue="0")int type,
			HttpServletRequest request, HttpServletResponse response, Model model){
		//处理mobile参数
		Order order = shopService.findByOrderNo(orderNo);
		if (order==null) {
			return "redirect:"+Global.getFrontPath()+"/shops/sysAlert?code="+MessageEnum.NOT_EXISTS_ORDER.getCode();
		}
		if (order.getPayType().equals("2")) { //支付宝
			if(type==0){
				String redirectPage = PayBase.alipaySubmit_WX(order, type);
				return "redirect:"+redirectPage;
			}else {
				String redirectPage = PayBase.alipaySubmit_WX(order, type, type);
				return "redirect:"+redirectPage;
			}
		}else if (order.getPayType().equals("3")) { //银联
			if(type==0){
				String redirectPage = PayBase.unionpaySubmit_WX(request, order);
				return "redirect:"+redirectPage;
			}else {
				String redirectPage = PayBase.unionpaySubmit_WX(request, order, type);
				return "redirect:"+redirectPage;
			}
		}
		return null;
	}
	
	
	@RequestMapping(value = "shops/shoping/order/toPayPC")
	public String orderToPayPC(
			String orderNo, 
			@RequestParam(value="type", required=true, defaultValue="0")int type,
			HttpServletRequest request, HttpServletResponse response, Model model){
		//处理mobile参数
		Order order = shopService.findByOrderNo(orderNo);
		if (order==null) {
			return "redirect:"+Global.getFrontPath()+"/shops/sysAlert?code="+MessageEnum.NOT_EXISTS_ORDER.getCode();
		}
		if (order.getPayType().equals("2")) { //支付宝
			if(type==0){
				String redirectPage = PayBase.alipaySubmit_PC(order, type);
				return "redirect:"+redirectPage;
			}else {
				String redirectPage = PayBase.alipaySubmit_PC(order, type, type);
				return "redirect:"+redirectPage;
			}
		}else if (order.getPayType().equals("3")) { //银联
			if(type==0){
				String redirectPage = PayBase.unionpaySubmit_PC(request, order);
				return "redirect:"+redirectPage;
			}else {
				String redirectPage = PayBase.unionpaySubmit_PC(request, order, type);
				return "redirect:"+redirectPage;
			}
		}
		return null;
	}
}
